package com.zhang.service.impl;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.zhang.dao.LoveDao;
import com.zhang.dao.UserDao;
import com.zhang.dao.impl.LoveDaoImpl;
import com.zhang.dao.impl.UserDaoImpl;
import com.zhang.domain.Love;
import com.zhang.domain.Page;
import com.zhang.domain.User;
import com.zhang.service.UserService;

import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDaoImpl();
    private LoveDao loveDao = new LoveDaoImpl();

    @Override
    public void addUser(User user) {

        userDao.save(user);
        List<Love> loves = user.getLove();
        for (Love love : loves) {
            userDao.saveUserLove(user.getId(), love.getId());
        }

    }

    @Override
    public User login(String username, String password) {
        return userDao.login(username, password);
    }

    @Override
    public Page<User> queryPage(Map<String, Object> condition, int currentPage, int row) {
        Page<User> page = new Page<>();

        int currentPage1 = currentPage;
        int row1 = row;
        int totalCount = userDao.getTotal(condition);
        int totalPage = totalCount % row == 0 ? totalCount / row : (totalCount / row) + 1;
        List<User> list = userDao.Page(condition, (currentPage1 - 1) * 5, row1);
        for (User user : list) {
            List<Love> loves = loveDao.selectLove(user.getId());
            user.setLove(loves);
        }

        page.setList(list);
        page.setCurrentPage(currentPage);
        page.setRow(row);
        page.setTotalCount(totalCount);
        page.setTotalPage(totalPage);


        return page;
    }

    @Override
    public void delUser(int id) {
        userDao.delUser(id);
        userDao.delUserLove(id);
    }

    @Override
    public User findUser(int id) {
        User user = userDao.select(id);

        List<Love> loves = loveDao.selectLove(id);
        user.setLove(loves);
        return user;
    }

    @Override
    public void updateUser(User user) {
        userDao.update(user);
        userDao.delLove(user.getId());
        List<Love> loves = user.getLove();
        for (Love love : loves) {
            userDao.saveUserLove(user.getId(), love.getId());
        }

    }


}












